﻿using System.Collections.ObjectModel;
using System.Windows.Input;
using DevExpress.Mvvm;
using EduAssess.Models;
using EduAssess.Services;
using EduAssess.Views;

namespace EduAssess.ViewModels;

public class TestListPageViewModel : BindableBase
    {
        private readonly PageNavigationService _navigation;
        private readonly Repository _repository;
        private readonly TestState _testState;

        public ObservableCollection<Test> Tests { get; set; }
        private Test? _selectedTest;
        public Test? SelectedTest
        {
            get => _selectedTest;
            set
            {
                _selectedTest = value;
                _testState.CurrentTest = SelectedTest;
                ShowTestDialog();
            }
        }
        public TestListPageViewModel(PageNavigationService navigationService, Repository repository, TestState testState)
        {
            _navigation = navigationService;
            _repository = repository;
            _testState = testState;

            Tests = new ObservableCollection<Test>(_repository.FindAll<Test>().OrderByDescending(x => x.CreationDate));
            
        }

        public ICommand OpenTestCommand => new DelegateCommand<Guid>((id) =>
        {
            _testState.CurrentTest = Tests.FirstOrDefault(x => x.Id == id);
            ShowTestDialog();      
        });

        public ICommand EditTestCommand => new DelegateCommand<Guid>((id) =>
        {
            _testState.CurrentTest = Tests.FirstOrDefault(x => x.Id == id);
            _navigation.Navigate(new CreateTestPage());
        });

        public ICommand DeleteTestCommand => new DelegateCommand<Guid>((id) =>
        {
            _repository.Delete<Test>(id);
            Tests.Remove(Tests.FirstOrDefault(x => x.Id == id)!);
        });

        private void ShowTestDialog()
        {
            var dialogWindow = new TestDialogWindow();
            if (dialogWindow.ShowDialog() == true)
                _navigation.Navigate(new TestPage());
        }
    }